#pragma once
#include "TcpServer.hpp"
#include "HttpProtocal.hpp"

using namespace HttpProtocalModule;

class HttpServer
{
public:
    HttpServer(uint16_t port):
        _tcvr(std::make_unique<TcpServer>(port)),
        _port(port)
    {}

    void InitServer()
    {
        _tcvr->InitServer(HandlerRequest);
        _tcvr->Loop();
    }
    static void HandlerRequest(std::string request,std::shared_ptr<TcpSocket> tcsr)
    {
        // 第二个参数负责返回的作用
        // 拿到了一个request
        // std::cout << "得到的报文:" << request << std::endl;
        Request req;
        
        bool isReadScs = true;
        if(req.Deserialize(request) == false){
            // 
            LOG(LogLevel::ERROR) << "反序列化失败";
            isReadScs = false;
        }
       
        // std::cout << "method:" << req.Method() << " uri:" << req.Uri() << " version:" << req.Version() << std::endl;
         
        if(isReadScs)
        {
            // 构建应答
            Response rsps;
        
            rsps.Build(req);
            std::string rsps_str;
            rsps.Serialize(&rsps_str);
            //std::cout << "返回的Response:" << std::endl;
            //std::cout << rsps_str << std::endl; // 打印我们序列化的数据
            tcsr->SendTo(rsps_str);
            // LOG(LogLevel::DEBUG) << "sendto sucessfully : " << rsps_str;
        }

        bool ret = tcsr->Close(tcsr->SockForCommunicate());
        if(ret) LOG(LogLevel::DEBUG) << "close successfully";
        else LOG(LogLevel::ERROR) << "close fail";
    }

    void Stop()
    {
        _tcvr->Stop();
    }
private:
    std::unique_ptr<TcpServer> _tcvr;
    uint16_t _port;
};